<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul
          class="cart-list"
          v-for="cartInfo in cartInfoList"
          :key="cartInfo.id"
        >
          <li class="cart-list-con1">
            <input
              type="checkbox"
              name="chk_list"
              :checked="!!cartInfo.isChecked"
              @change="checkCartInfoState(cartInfo)"
            />
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl" />
            <div class="item-msg">{{ cartInfo.skuName }}</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}.00</span>
          </li>
          <li class="cart-list-con5">
            <a
              href="javascript:void(0)"
              class="mins"
              @click="changeSkuNum('decrement', cartInfo)"
              >-</a
            >
            <input
              autocomplete="off"
              type="text"
              :value="cartInfo.skuNum"
              minnum="1"
              class="itxt"
              @change="changeSkuNum('change', cartInfo, $event)"
            />
            <a
              href="javascript:void(0)"
              class="plus"
              @click="changeSkuNum('increment', cartInfo)"
              >+</a
            >
          </li>
          <li class="cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a
              href="javascript:;"
              class="sindelet"
              @click="showDialogByDelOne(cartInfo.skuId)"
              >删除</a
            >
            <br />
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="checkAll" />
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="showDialogByDelSelected"
          >删除选中的商品</a
        >
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">
          已选择 <span>{{ seletedCount }}</span
          >件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ selectedMoney }}.00</i>
        </div>
        <div class="sumbtn">
          <a class="sum-btn" href="javascript:;" @click="$router.push('/trade')"
            >结算</a
          >
        </div>
      </div>
    </div>

    <!-- 弹出框 -->
    <Dialog :visible.sync="visible">
      <template v-slot:header>
        <p>提示</p>
      </template>
      <template>
        <p>
          您真的要删除<span style="color: red">{{
            isDelOne ? "此条" : "这些选中的"
          }}</span
          >数据吗？
        </p>
      </template>
      <template #footer>
        <div class="btn-footer">
          <button class="btn btn-cancle" @click="visible = false">取消</button>
          <button class="btn btn-primary" @click="delShopCartInfo">确定</button>
        </div>
      </template>
    </Dialog>
  </div>
</template>

<script>
import {
  reqGetShopCartListData,
  reqChangeShopCartInfoState,
  reqChangeAllShopCartInfoState,
  reqDelOneShopCartInfo,
  reqDelSelectedShopCartInfo,
  reqAddOrUpdateSkuInfoToShopCart,
} from "@/api";
import { skuNumReg } from "@/utils/reg";

export default {
  name: "ShopCart",
  data() {
    return {
      cartInfoList: [],
      // skuIdList: [], // 批量更新商品的选中状态数据
      visible: false, // 默认不弹框
      isDelOne: false,
      skuId: 0,
      skuIdList: [],
      leftCartInfoList: [],
      num: 0,
      timeId: null,
    };
  },
  mounted() {
    this.getShopCartListData();
  },
  computed: {
    //  全选全不选
    checkAll: {
      get() {
        return (
          this.cartInfoList.every((item) => item.isChecked === 1) &&
          this.cartInfoList.length
        );
      },
      async set(val) {
        const skuIdList = [];
        this.cartInfoList.forEach((item) => {
          item.isChecked = val ? 1 : 0;
          skuIdList.push(item.skuId);
        });
        const result = await reqChangeAllShopCartInfoState(
          skuIdList,
          val ? 1 : 0
        );
        if (result.code === 200) {
          alert("批量更新成功");
        } else {
          console.log(result.message);
        }
      },
    },
    // 统计选择和商品数量
    seletedCount() {
      return this.cartInfoList.reduce((prev, item) => prev + item.isChecked, 0);
    },
    // 计算付款的总金额
    selectedMoney() {
      return this.cartInfoList.reduce(
        (prev, item) => prev + item.skuPrice * item.skuNum * item.isChecked,
        0
      );
    },
  },
  methods: {
    // 1 获取购物车商品列表数据
    async getShopCartListData() {
      const result = await reqGetShopCartListData();
      console.log("shopcart", result);
      if (result.code === 200) {
        this.cartInfoList = result.data[0] ? result.data[0].cartInfoList : [];
      } else {
        console.log(result.message);
      }
    },
    // 2 更改商品的选中状态
    async checkCartInfoState(cartInfo) {
      cartInfo.isChecked = 1 - cartInfo.isChecked;
      // 使用skuId
      const result = await reqChangeShopCartInfoState(
        cartInfo.skuId,
        cartInfo.isChecked
      );
      if (result.code === 200) {
        alert("状态更新成功");
      } else {
        console.log(result.message);
      }
    },
    // 3 删除一条商品弹出对话框
    showDialogByDelOne(skuId) {
      this.visible = true; // 显示弹框
      this.isDelOne = true;
      this.skuId = skuId;
    },
    // 4 单击批量删除按钮弹出对话框
    showDialogByDelSelected() {
      // 弹出对话框
      this.visible = true;
      // 将isDelOne 进行重新赋值
      this.isDelOne = false;
      // 获取选中商品的ID
      this.skuIdList = []; // 将原来的待删除商品id清除
      this.cartInfoList.forEach((cartInfo) => {
        if (cartInfo.isChecked === 1) {
          this.skuIdList.push(cartInfo.skuId);
        } else {
          // 过滤出未删除的数据
          this.leftCartInfoList.push(cartInfo);
        }
      });
    },
    // 5 单击按钮 删除购物车数据
    async delShopCartInfo() {
      // 判断是删除一条还是多条
      if (this.isDelOne) {
        //  发送请求删除一条
        const result = await reqDelOneShopCartInfo(this.skuId);
        if (result.code === 200) {
          //  关闭弹框
          this.visible = false;
          // 重新发送请求 渲染
          this.cartInfoList = this.cartInfoList.filter(
            (cartInfo) => cartInfo.skuId !== this.skuId
          );
        } else {
          console.log(result.message);
        }
        return; // 代码不向下执行
      }
      // 此时 是批量删除购物车商品数据
      const result = await reqDelSelectedShopCartInfo(this.skuIdList);
      if (result.code === 200) {
        this.visible = false; // 关闭对话框
        this.cartInfoList = this.leftCartInfoList;
      } else {
        console.log(result.message);
      }
    },
    // 6 更改购物车种商品的数据
    changeSkuNum(type, cartInfo, e) {
      if(this.timeId) clearTimeout(this.timeId)
      // let num = 0; // 定义一个初始值
      let oldNum = cartInfo.skuNum;
      switch (type) {
        case "increment":
          if (cartInfo.skuNum < 200) {
            cartInfo.skuNum++;
            this.num++;
          }
          break;
        case "decrement":
          if (cartInfo.skuNum > 1) {
            cartInfo.skuNum--;
            this.num--;
          }
          break;
        case "change":
          // 获取新输入得值
          let newNum = e.target.value;
          if (skuNumReg.test(newNum)) {
            cartInfo.skuNum = newNum;
            this.num = newNum - oldNum; // 更改后的插值
            if (newNum > 200) {
              cartInfo.skuNum = 200;
              this.num = 200 - oldNum;
            }
          } else {
            e.target.value = oldNum; // 恢复页面原来的数据
          }
          break;
      }
      if (this.num === 0) return;
      this.timeId = setTimeout(async () =>{
        const result = await reqAddOrUpdateSkuInfoToShopCart(cartInfo.skuId,this.num);
        if(result.code === 200) {
          this.num = 0
          this.$message({
            type:'success',
            message:'数据更新成功'
          })
        }else {
          console.log(result.message);
        }
      },700)
    },
    beforeDestroy () {
      // 组件销毁之前要消除定时器
      clearTimeout(this.timeId)
    }
  },
};
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;
  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }
  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;
      & > div {
        float: left;
      }
      .cart-th1 {
        width: 25%;
        input {
          vertical-align: middle;
        }
        span {
          vertical-align: middle;
        }
      }
      .cart-th2 {
        width: 25%;
      }
      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;
      }
    }
    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;
      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;
        & > li {
          float: left;
        }
        .cart-list-con1 {
          width: 15%;
        }
        .cart-list-con2 {
          width: 35%;
          img {
            width: 82px;
            height: 82px;
            float: left;
          }
          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }
        .cart-list-con4 {
          width: 10%;
        }
        .cart-list-con5 {
          width: 17%;
          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 10%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 13%;

          a {
            color: #666;
          }
        }
      }
    }
  }
  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
.btn-footer {
  position: absolute;
  right: 2px;
  bottom: 20px;
  .btn {
    width: 70px;
    height: 40px;
    border: none;
    border-radius: 6px;
    margin-right: 20px;
    cursor: pointer;
  }
  .btn-primary {
    color: #fff;
    background-color: #409eff;
    &:hover {
      background-color: #66b1ff;
    }
  }
  .btn-cancle {
    border: 1px solid #ccc;
    &:hover {
      background-color: #ecf5ff;
      color: #66b1ff;
    }
  }
}
</style>